/*
 * @Date: 2024-04-01 09:33:35
 * @LastEditors: bingkui.wu
 * @LastEditTime: 2024-04-02 11:21:36
 * @Description: 更新用户信息接口
 */
import { REQUEST } from "#type/request";
import Response from "@common/Response";
import { User, IWord } from "@models/User";
import verifyToken from "@/helper/verifyToken";

const root: REQUEST.BASIC = {
  auth: false,
  method: "post",
  request: async (ctx: any) => {
    try {
      /**
       * starCount: 需要增加的星星数量
       * correctWords: 本次听写正确的单词 {wordId, eng, result}
       * incorrectWords: 本次听写错误的单词 {wordId, eng, result}
       */
      const { starCount, correctWords, incorrectWords, nickName } = ctx.request
        .body as {
        starCount: number;
        correctWords: IWord[];
        incorrectWords: IWord[];
        nickName: string;
      };
      //   console.log(curTime(), "update-user 调用了: starCount=", starCount, ", correctWords=", correctWords, ", incorrectWords=", incorrectWords);
      const user = await verifyToken(ctx.header.authorization);

      const { _id } = user as any;
      let obj = await User.findOne({ _id }).lean().exec();
      if (obj) {
        const updatedProps = {
          starCount: obj.starCount || 0,
          correctWords: obj.correctWords || [],
          incorrectWords: obj.incorrectWords || [],
          nickName: obj.nickName,
        };
        if (nickName) {
          updatedProps.nickName = nickName;
        }
        if (starCount) {
          updatedProps.starCount += starCount;
        }
        if (correctWords) {
          // 添加答对的单词，
          updatedProps.correctWords = [
            ...updatedProps.correctWords,
            ...correctWords.filter(
              (m) =>
                !updatedProps.correctWords.find((n) => n.wordId === m.wordId) // 已存在的不需要添加
            ),
          ];
          // 去掉答错的单词
          updatedProps.correctWords = updatedProps.correctWords.filter(
            (m) => !incorrectWords.find((n) => n.wordId === m.wordId)
          );
        }
        if (incorrectWords) {
          // 添加答错的单词，
          updatedProps.incorrectWords = [
            ...updatedProps.incorrectWords,
            ...incorrectWords.filter(
              (m) =>
                !updatedProps.incorrectWords.find((n) => n.wordId === m.wordId) // 已存在的不需要添加
            ),
          ];
          // 去掉答对的单词
          updatedProps.incorrectWords = updatedProps.incorrectWords.filter(
            (m) => !correctWords.find((n: IWord) => n.wordId === m.wordId)
          );
        }
        await User.updateOne({ _id }, updatedProps).lean().exec();
        return Response.Success(updatedProps);
      } else {
        return Response.Error(10001, `没有找到用户:${_id}`);
      }
    } catch (err) {
      console.log(err);
      return err;
    }
  },
};

export default root;
